﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

using EHTWebsite.Code;

/// <summary>
/// Author: toanvt
/// CreatedDate: 13/12/2011
/// Description: Inser, Update chuyên mục tin tức
/// </summary>
public partial class AdminNewsCategoryIU : System.Web.UI.Page
{
    public Int32 DanhMucTinTucID = HangSo.DEFAULT_ID;
    public String message = "";
    private DataTable dtNewsCategorys = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            DanhMucTinTucID = Int32.Parse(Request.QueryString["DanhMucTinTucID"].ToString());
        }
        catch (Exception)
        {
            DanhMucTinTucID = HangSo.DEFAULT_ID;
        }

        try
        {
            message = Request.QueryString["Message"].ToString();
        }
        catch (Exception ex)
        {
            message = "";
        }

        //hiển thị Message nếu có giá trị Message gửi sang từ màn hình nguồn
        this.lbMessage.Text = message;
        this.lbMessage.CssClass = "BlueCorlor";
        
        if (!Page.IsPostBack)
        {
            dtNewsCategorys = DanhMucTinTucProvider.GetDanhsachtintucForBackEnd().Tables[0];
            // tao danh muc tin tuc trong drop dow list
            CreateDDLCategory(0, 0);
            this.ddlChuyenMucCha.Items.Insert(0, new ListItem("----Danh mục tin tức----", "0"));

            if (DanhMucTinTucID == -1)
            {
                ViewState["action"] = HangSo.ACTION_ADD;
                this.lbAdminNewCategory.Text = "Thêm mơi chuyên mục tin tức";
            }
            else
            {
                DanhMucTinTuc theDanhMucTinTuc = DanhMucTinTucProvider.GetDanhMucTinTucByDanhMucID(DanhMucTinTucID);

                if (theDanhMucTinTuc != null)
                {
                    txtTenDanhMucTinTucVN.Text = theDanhMucTinTuc.TenDanhMucTinTucVN.ToString();
                    txtTenDanhMucTinTucOther.Text = theDanhMucTinTuc.TenDanhMucTinTucOther.ToString();
                    ddlChuyenMucCha.SelectedValue = theDanhMucTinTuc.ChuyenMucChaID.ToString();                    
                    txtSapXep.Text = theDanhMucTinTuc.SapXep.ToString();
                    lbtrangthai.Text = theDanhMucTinTuc.Trangthai.ToString();
                    this.ImagIcon.ImageUrl = theDanhMucTinTuc.Icon.ToString();
                    ViewState["Icon"] = theDanhMucTinTuc.Icon;
                }
                else
                {
                    Response.Redirect("AdminNewsCategorys.aspx");
                }

                ViewState["DanhMucID"] = theDanhMucTinTuc.DanhMucTinTucID;
                ViewState["action"] = HangSo.ACTION_UPDATE;
                this.lbAdminNewCategory.Text = "Sửa chuyên mục tin tức";
            }
        }
    }

    private Boolean ValidateData()
    {
        this.lbMessage.Text = "";
        this.lbMessage.CssClass = "";

        String message = "";
        Boolean isSuccess = true;
        string sExtendsion = ".gif|.GIF|.jpg|.JPG|.png|.PNG";

        try
        {
            if (this.fulIcon.HasFile && sExtendsion.IndexOf(Path.GetExtension(fulIcon.PostedFile.FileName)) < 0)
            {
                isSuccess = false;
                message = "Upload picture only.";
            }
        }
        catch (Exception ex)
        {
            isSuccess = false;
        }

        if (!isSuccess)

            lbMessage.Text = message;
        return isSuccess;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        String action = ViewState["action"].ToString();

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            DanhMucTinTuc theDanhMucTinTuc = new DanhMucTinTuc();
            theDanhMucTinTuc.TenDanhMucTinTucVN = txtTenDanhMucTinTucVN.Text.Trim();
            theDanhMucTinTuc.TenDanhMucTinTucOther = txtTenDanhMucTinTucOther.Text.Trim();
            theDanhMucTinTuc.ChuyenMucChaID = Int32.Parse(ddlChuyenMucCha.SelectedValue.ToString());
            theDanhMucTinTuc.NhomDanhMucID = -1;           
            try
            {
                theDanhMucTinTuc.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            }
            catch (Exception ex)
            {
                theDanhMucTinTuc.SapXep = 1;
            }

            if (this.fulIcon.HasFile)
            {
                // Rezise anh truoc khi up len server
                // start
                String pathAvatars = Server.MapPath("~/");
                try
                {

                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulIcon.PostedFile.InputStream);
                    int thumbWidth = 30;
                    int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));

                    System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                    Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    oGraphic.DrawImage(oImg, oRectangle);
                    oThumbNail.Save(pathAvatars + "\\ImageDatas\\News\\IconNhomTinTuc\\" + fulIcon.FileName.Trim());
                    theDanhMucTinTuc.Icon = "~//ImageDatas//News//IconNhomTinTuc//" + fulIcon.FileName.Trim();
                    oImg.Dispose();
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
                //end
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    theDanhMucTinTuc.Icon = ViewState["Icon"].ToString();
                }
                else
                {
                    theDanhMucTinTuc.Icon = "~//ImageDatas//News//IconNhomTinTuc//noImage.gif";
                }
            }

            if (action == HangSo.ACTION_ADD)
            {                
                theDanhMucTinTuc.Trangthai = false;
                DanhMucTinTucProvider.IUDanhMucTinTuc(theDanhMucTinTuc, true);
            }
            else
            {
                theDanhMucTinTuc.DanhMucTinTucID = Int32.Parse(ViewState["DanhMucID"].ToString());
                theDanhMucTinTuc.Trangthai = Boolean.Parse(lbtrangthai.Text.Trim());
                DanhMucTinTucProvider.IUDanhMucTinTuc(theDanhMucTinTuc, false);
            }

            Response.Redirect("AdminNewsCategorys.aspx?DanhMucTinTucID=" + DanhMucTinTucID);
        }
    }

    /// <summary>
    /// Author : chiennv
    /// CreatedDate : 07/02/2012
    /// Description : tạo DropDownList bằng đệ quy
    /// </summary>
    /// <param name="ChuyenMucChaID"></param>
    private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
    {
        String preString = "";

        for (Int32 i = 0; i < level; ++i)
        {
            preString += "--";
        }

        DataRow[] drCategorysSub = dtNewsCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
        Int32 amountOfCategorySub = drCategorysSub.Count();

        //Điểm dừng đệ quy
        if (amountOfCategorySub == 0)
            return;

        for (Int32 i = 0; i < amountOfCategorySub; ++i)
        {
            Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucTinTucID"].ToString());

            ListItem li = new ListItem(preString + drCategorysSub[i]["TenDanhMucTinTucVN"].ToString(), drCategorysSub[i]["DanhMucTinTucID"].ToString());
            this.ddlChuyenMucCha.Items.Add(li);
            CreateDDLCategory(subCategoryID, level + 1);
        }
    }

    protected void ddlNhomDanhMuc_SelectedIndexChanged(object sender, EventArgs e)
    {
        //(Int32.Parse(ddlNhomDanhMuc.SelectedValue));
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("AdminNewsCategorys.aspx?DanhMucTinTucID=" + DanhMucTinTucID);
    }

    protected void btnApply_Click(object sender, EventArgs e)
    {
        Int32 danhMucTinTucIDOut = -1;
        String action = ViewState["action"].ToString();

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            DanhMucTinTuc theDanhMucTinTuc = new DanhMucTinTuc();
            theDanhMucTinTuc.TenDanhMucTinTucVN = txtTenDanhMucTinTucVN.Text.Trim();
            theDanhMucTinTuc.TenDanhMucTinTucOther = txtTenDanhMucTinTucOther.Text.Trim();
            theDanhMucTinTuc.ChuyenMucChaID = Int32.Parse(ddlChuyenMucCha.SelectedValue.ToString());
            theDanhMucTinTuc.NhomDanhMucID = -1;

            try
            {
                theDanhMucTinTuc.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            }
            catch (Exception ex)
            {
                theDanhMucTinTuc.SapXep = 1;
            }

            if (this.fulIcon.HasFile)
            {
                // Rezise anh truoc khi up len server
                // start
                String pathAvatars = Server.MapPath("~/");
                try
                {

                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulIcon.PostedFile.InputStream);
                    int thumbWidth = 30;
                    int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));

                    System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                    Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    oGraphic.DrawImage(oImg, oRectangle);
                    oThumbNail.Save(pathAvatars + "\\ImageDatas\\News\\IconNhomTinTuc\\" + fulIcon.FileName.Trim());
                    theDanhMucTinTuc.Icon = "~//ImageDatas//News//IconNhomTinTuc//" + fulIcon.FileName.Trim();
                    oImg.Dispose();
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
                //end
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    theDanhMucTinTuc.Icon = ViewState["Icon"].ToString();
                }
                else
                {
                    theDanhMucTinTuc.Icon = "~//ImageDatas//News//IconNhomTinTuc//noImage.gif";
                }
            }

            if (action == HangSo.ACTION_ADD)
            {
                theDanhMucTinTuc.Trangthai = false;
                danhMucTinTucIDOut = DanhMucTinTucProvider.IUDanhMucTinTuc(theDanhMucTinTuc, true);
            }
            else
            {
                theDanhMucTinTuc.DanhMucTinTucID = Int32.Parse(ViewState["DanhMucID"].ToString());
                theDanhMucTinTuc.Trangthai = Boolean.Parse(lbtrangthai.Text.Trim());
                danhMucTinTucIDOut = DanhMucTinTucProvider.IUDanhMucTinTuc(theDanhMucTinTuc, false);
            }

            Response.Redirect("AdminNewsCategoryIU.aspx?DanhMucTinTucID=" + danhMucTinTucIDOut.ToString() + "&Message=Lưu thành công");
        }
    }
}
